

import React, { useState, useRef, useEffect } from 'react';
import { View, Text, TextInput, TouchableOpacity, ScrollView, Alert, KeyboardAvoidingView, Platform, } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { LinearGradient } from 'expo-linear-gradient';
import { FontAwesome6 } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import AsyncStorage from '@react-native-async-storage/async-storage';
import styles from './styles';

type LoginType = 'password' | 'sms';

interface LoginFormData {
  username: string;
  password: string;
  phone: string;
  smsCode: string;
}

const LoginScreen: React.FC = () => {
  const router = useRouter();
  
  // 状态管理
  const [currentLoginType, setCurrentLoginType] = useState<LoginType>('password');
  const [isPasswordVisible, setIsPasswordVisible] = useState(false);
  const [isRememberPasswordChecked, setIsRememberPasswordChecked] = useState(false);
  const [isAutoLoginChecked, setIsAutoLoginChecked] = useState(false);
  const [isLoginLoading, setIsLoginLoading] = useState(false);
  const [smsCountdownSeconds, setSmsCountdownSeconds] = useState(0);
  const [errorMessageText, setErrorMessageText] = useState('');
  const [successMessageText, setSuccessMessageText] = useState('');
  const [isErrorMessageVisible, setIsErrorMessageVisible] = useState(false);
  const [isSuccessMessageVisible, setIsSuccessMessageVisible] = useState(false);
  
  // 表单数据
  const [loginFormData, setLoginFormData] = useState<LoginFormData>({
    username: '',
    password: '',
    phone: '',
    smsCode: '',
  });

  // 计时器引用
  const smsCountdownTimerRef = useRef<number | null>(null);

  // 清理计时器
  useEffect(() => {
    return () => {
      if (smsCountdownTimerRef.current) {
        clearInterval(smsCountdownTimerRef.current);
      }
    };
  }, []);

  // 检查自动登录
  useEffect(() => {
    checkAutoLoginSettings();
  }, []);

  const checkAutoLoginSettings = async () => {
    try {
      const autoLoginSetting = await AsyncStorage.getItem('@autoLogin');
      const savedUsername = await AsyncStorage.getItem('@username');
      const savedPassword = await AsyncStorage.getItem('@password');
      
      if (autoLoginSetting === 'true' && savedUsername && savedPassword) {
        setLoginFormData(prev => ({
          ...prev,
          username: savedUsername,
          password: savedPassword,
        }));
        setIsRememberPasswordChecked(true);
        setIsAutoLoginChecked(true);
        
        // 自动提交登录
        setTimeout(() => {
          handleLoginSubmit();
        }, 500);
      }
    } catch (error) {
      console.log('检查自动登录失败:', error);
    }
  };

  const switchToPasswordLoginType = () => {
    setCurrentLoginType('password');
    clearAllMessages();
  };

  const switchToSmsLoginType = () => {
    setCurrentLoginType('sms');
    clearAllMessages();
  };

  const togglePasswordVisibility = () => {
    setIsPasswordVisible(!isPasswordVisible);
  };

  const toggleRememberPasswordCheckbox = () => {
    setIsRememberPasswordChecked(!isRememberPasswordChecked);
  };

  const toggleAutoLoginCheckbox = () => {
    setIsAutoLoginChecked(!isAutoLoginChecked);
  };

  const startSmsCountdownTimer = () => {
    setSmsCountdownSeconds(60);
    
    smsCountdownTimerRef.current = setInterval(() => {
      setSmsCountdownSeconds(prev => {
        if (prev <= 1) {
          if (smsCountdownTimerRef.current) {
            clearInterval(smsCountdownTimerRef.current);
          }
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };

  const handleGetSmsCodePress = () => {
    const phoneNumber = loginFormData.phone.trim();
    
    if (!phoneNumber) {
      showErrorMessage('请输入手机号');
      return;
    }
    
    if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
      showErrorMessage('请输入正确的手机号');
      return;
    }
    
    // 模拟发送验证码
    showSuccessMessage('验证码已发送');
    startSmsCountdownTimer();
  };

  const validatePasswordLoginForm = (): boolean => {
    const { username, password } = loginFormData;
    
    if (!username.trim()) {
      showErrorMessage('请输入用户名');
      return false;
    }
    
    if (!password.trim()) {
      showErrorMessage('请输入密码');
      return false;
    }
    
    return true;
  };

  const validateSmsLoginForm = (): boolean => {
    const { phone, smsCode } = loginFormData;
    
    if (!phone.trim()) {
      showErrorMessage('请输入手机号');
      return false;
    }
    
    if (!/^1[3-9]\d{9}$/.test(phone.trim())) {
      showErrorMessage('请输入正确的手机号');
      return false;
    }
    
    if (!smsCode.trim()) {
      showErrorMessage('请输入验证码');
      return false;
    }
    
    if (smsCode.trim().length !== 6) {
      showErrorMessage('验证码应为6位数字');
      return false;
    }
    
    return true;
  };

  const showErrorMessage = (message: string) => {
    clearAllMessages();
    setErrorMessageText(message);
    setIsErrorMessageVisible(true);
  };

  const showSuccessMessage = (message: string) => {
    clearAllMessages();
    setSuccessMessageText(message);
    setIsSuccessMessageVisible(true);
  };

  const clearAllMessages = () => {
    setErrorMessageText('');
    setSuccessMessageText('');
    setIsErrorMessageVisible(false);
    setIsSuccessMessageVisible(false);
  };

  const saveLoginSettingsToStorage = async () => {
    try {
      if (isRememberPasswordChecked) {
        await AsyncStorage.setItem('@username', loginFormData.username);
        await AsyncStorage.setItem('@password', loginFormData.password);
      } else {
        await AsyncStorage.removeItem('@username');
        await AsyncStorage.removeItem('@password');
      }
      
      await AsyncStorage.setItem('@autoLogin', isAutoLoginChecked ? 'true' : 'false');
    } catch (error) {
      console.log('保存登录设置失败:', error);
    }
  };

  const handleLoginSubmit = async () => {
    clearAllMessages();
    
    // 验证表单
    let isFormValid = false;
    if (currentLoginType === 'password') {
      isFormValid = validatePasswordLoginForm();
    } else {
      isFormValid = validateSmsLoginForm();
    }
    
    if (!isFormValid) {
      return;
    }
    
    // 显示加载状态
    setIsLoginLoading(true);
    
    try {
      // 模拟登录请求
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // 保存登录设置
      await saveLoginSettingsToStorage();
      
      // 登录成功，跳转到首页
      router.replace('/p-home');
    } catch (error) {
      showErrorMessage('登录失败，请重试');
    } finally {
      setIsLoginLoading(false);
    }
  };

  const updateFormDataField = (field: keyof LoginFormData, value: string) => {
    setLoginFormData(prev => ({
      ...prev,
      [field]: value,
    }));
  };

  const renderTabButton = (
    loginType: LoginType,
    tabTitle: string
  ) => {
    const isActiveTab = currentLoginType === loginType;
    
    return (
      <TouchableOpacity
        style={[
          styles.tabButton,
          isActiveTab ? styles.activeTabButton : styles.inactiveTabButton
        ]}
        onPress={loginType === 'password' ? switchToPasswordLoginType : switchToSmsLoginType}
        activeOpacity={0.8}
      >
        <Text style={[
          styles.tabButtonText,
          isActiveTab ? styles.activeTabButtonText : styles.inactiveTabButtonText
        ]}>
          {tabTitle}
        </Text>
      </TouchableOpacity>
    );
  };

  const renderCheckboxItem = (
    isChecked: boolean,
    checkboxLabel: string,
    onCheckboxToggle: () => void
  ) => (
    <TouchableOpacity
      style={styles.checkboxItemContainer}
      onPress={onCheckboxToggle}
      activeOpacity={0.7}
    >
      <View style={[
        styles.checkboxCustomContainer,
        isChecked ? styles.checkedCheckboxContainer : styles.uncheckedCheckboxContainer
      ]}>
        {isChecked && (
          <FontAwesome6 name="check" size={12} color="#ffffff" />
        )}
      </View>
      <Text style={styles.checkboxLabelText}>{checkboxLabel}</Text>
    </TouchableOpacity>
  );

  const renderErrorMessage = () => {
    if (!isErrorMessageVisible) return null;
    
    return (
      <View style={styles.errorMessageContainer}>
        <FontAwesome6 name="circle-exclamation" size={14} color="#ef4444" />
        <Text style={styles.errorMessageText}>{errorMessageText}</Text>
      </View>
    );
  };

  const renderSuccessMessage = () => {
    if (!isSuccessMessageVisible) return null;
    
    return (
      <View style={styles.successMessageContainer}>
        <FontAwesome6 name="circle-check" size={14} color="#10b981" />
        <Text style={styles.successMessageText}>{successMessageText}</Text>
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.safeAreaContainer}>
      <KeyboardAvoidingView
        style={styles.keyboardAvoidingContainer}
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      >
        <ScrollView
          style={styles.scrollContainer}
          contentContainerStyle={styles.scrollContentContainer}
          keyboardShouldPersistTaps="handled"
          showsVerticalScrollIndicator={false}
        >
          {/* Logo和标题区域 */}
          <View style={styles.logoSectionContainer}>
            <View style={styles.logoContainer}>
              <LinearGradient
                colors={['#6366f1', '#8b5cf6']}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
                style={styles.appLogoGradient}
              >
                <FontAwesome6 name="layer-group" size={48} color="#ffffff" />
              </LinearGradient>
              
              <Text style={styles.appNameText}>流批通</Text>
              <Text style={styles.appSloganText}>高效移动审批平台</Text>
            </View>

            {/* 登录方式切换 */}
            <View style={styles.loginTypeTabsContainer}>
              {renderTabButton('password', '账号密码登录')}
              {renderTabButton('sms', '验证码登录')}
            </View>

            {/* 登录表单 */}
            <View style={styles.loginFormContainer}>
              {/* 账号密码登录表单 */}
              {currentLoginType === 'password' && (
                <View style={styles.passwordLoginFormContainer}>
                  <View style={styles.inputFieldContainer}>
                    <Text style={styles.inputFieldLabel}>用户名</Text>
                    <View style={styles.inputFieldWrapper}>
                      <TextInput
                        style={styles.textInputField}
                        placeholder="请输入用户名"
                        placeholderTextColor="#6b7280"
                        value={loginFormData.username}
                        onChangeText={(value) => updateFormDataField('username', value)}
                        autoCapitalize="none"
                        autoCorrect={false}
                      />
                      <FontAwesome6 name="user" size={16} color="#6b7280" style={styles.inputFieldIcon} />
                    </View>
                  </View>

                  <View style={styles.inputFieldContainer}>
                    <Text style={styles.inputFieldLabel}>密码</Text>
                    <View style={styles.inputFieldWrapper}>
                      <TextInput
                        style={[styles.textInputField, styles.passwordInputField]}
                        placeholder="请输入密码"
                        placeholderTextColor="#6b7280"
                        value={loginFormData.password}
                        onChangeText={(value) => updateFormDataField('password', value)}
                        secureTextEntry={!isPasswordVisible}
                        autoCapitalize="none"
                        autoCorrect={false}
                      />
                      <TouchableOpacity
                        style={styles.passwordToggleButton}
                        onPress={togglePasswordVisibility}
                        activeOpacity={0.7}
                      >
                        <FontAwesome6
                          name={isPasswordVisible ? 'eye-slash' : 'eye'}
                          size={16}
                          color="#6b7280"
                        />
                      </TouchableOpacity>
                    </View>
                  </View>
                </View>
              )}

              {/* 验证码登录表单 */}
              {currentLoginType === 'sms' && (
                <View style={styles.smsLoginFormContainer}>
                  <View style={styles.inputFieldContainer}>
                    <Text style={styles.inputFieldLabel}>手机号</Text>
                    <View style={styles.inputFieldWrapper}>
                      <TextInput
                        style={styles.textInputField}
                        placeholder="请输入手机号"
                        placeholderTextColor="#6b7280"
                        value={loginFormData.phone}
                        onChangeText={(value) => updateFormDataField('phone', value)}
                        keyboardType="phone-pad"
                        maxLength={11}
                      />
                      <FontAwesome6 name="mobile-screen" size={16} color="#6b7280" style={styles.inputFieldIcon} />
                    </View>
                  </View>

                  <View style={styles.inputFieldContainer}>
                    <Text style={styles.inputFieldLabel}>验证码</Text>
                    <View style={styles.smsCodeInputWrapper}>
                      <TextInput
                        style={styles.smsCodeTextInput}
                        placeholder="请输入验证码"
                        placeholderTextColor="#6b7280"
                        value={loginFormData.smsCode}
                        onChangeText={(value) => updateFormDataField('smsCode', value)}
                        keyboardType="number-pad"
                        maxLength={6}
                      />
                      <TouchableOpacity
                        style={[
                          styles.getSmsCodeButton,
                          smsCountdownSeconds > 0 && styles.disabledGetSmsCodeButton
                        ]}
                        onPress={handleGetSmsCodePress}
                        disabled={smsCountdownSeconds > 0}
                        activeOpacity={0.8}
                      >
                        <LinearGradient
                          colors={smsCountdownSeconds > 0 ? ['#9ca3af', '#9ca3af'] : ['#6366f1', '#8b5cf6']}
                          start={{ x: 0, y: 0 }}
                          end={{ x: 1, y: 1 }}
                          style={styles.getSmsCodeButtonGradient}
                        >
                          <Text style={styles.getSmsCodeButtonText}>
                            {smsCountdownSeconds > 0 ? `${smsCountdownSeconds}秒后重试` : '获取验证码'}
                          </Text>
                        </LinearGradient>
                      </TouchableOpacity>
                    </View>
                  </View>
                </View>
              )}

              {/* 选项设置 */}
              <View style={styles.loginOptionsContainer}>
                {renderCheckboxItem(
                  isRememberPasswordChecked,
                  '记住密码',
                  toggleRememberPasswordCheckbox
                )}
                {renderCheckboxItem(
                  isAutoLoginChecked,
                  '自动登录',
                  toggleAutoLoginCheckbox
                )}
              </View>

              {/* 错误/成功消息 */}
              <View style={styles.messageContainer}>
                {renderErrorMessage()}
                {renderSuccessMessage()}
              </View>

              {/* 登录按钮 */}
              <TouchableOpacity
                style={[
                  styles.loginButton,
                  isLoginLoading && styles.disabledLoginButton
                ]}
                onPress={handleLoginSubmit}
                disabled={isLoginLoading}
                activeOpacity={0.8}
              >
                <LinearGradient
                  colors={['#6366f1', '#8b5cf6']}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 1 }}
                  style={styles.loginButtonGradient}
                >
                  <Text style={styles.loginButtonText}>
                    {isLoginLoading ? '登录中...' : '登录'}
                  </Text>
                  {isLoginLoading && (
                    <FontAwesome6
                      name="spinner"
                      size={16}
                      color="#ffffff"
                      style={styles.loginLoadingSpinner}
                    />
                  )}
                </LinearGradient>
              </TouchableOpacity>
            </View>

            {/* 切换登录方式 */}
            <View style={styles.switchLoginTypeContainer}>
              <TouchableOpacity
                onPress={() => {
                  if (currentLoginType === 'password') {
                    switchToSmsLoginType();
                  } else {
                    switchToPasswordLoginType();
                  }
                }}
                activeOpacity={0.7}
              >
                <Text style={styles.switchLoginTypeLink}>
                  {currentLoginType === 'password' ? '切换到验证码登录' : '切换到账号密码登录'}
                </Text>
              </TouchableOpacity>
            </View>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
};

export default LoginScreen;

